package com.tianheng.wanzhou.datacollecting.jedis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * @Author: yujw
 * @Date: 2020/5/19 8:49
 * @Version 1.0
 */
@Component
public class JedisPoolUtil {
    //spring.redis配置属性读取
    @Value("${spring.redis.host}")
    private String host;
    @Value("${spring.redis.port}")
    private int port;
    @Value("${spring.redis.database}")
    private int database;
    @Value("${spring.redis.password}")
    private String password;
    @Value("${spring.redis.timeout}")
    private int timeout;


    @Autowired
    private JedisPoolConfig jedisPoolConfig;
    @Autowired
    private JedisPool jedisPool;

    @Bean //标注@Bean后表明返回对象会被当做一个Bean注册到Spring IoC容器
    public JedisPoolConfig createJedisPoolConfig(){
        JedisPoolConfig jedisPoolConfig = null;
        try{
            //创建连接池配置类
            jedisPoolConfig = new JedisPoolConfig();
            //控制连接池最多可以分配多少个jedis实例
            jedisPoolConfig.setMaxTotal(1024);
            //连接池最大空闲连接数
            jedisPoolConfig.setMaxIdle(20);
            //连接池最小空闲连接数，小于这个数会自动创建连接
            jedisPoolConfig.setMinIdle(8);
            //连接池最大阻塞时间
//            jedisPoolConfig.setMaxWaitMillis(1500);
            jedisPoolConfig.setMaxWaitMillis(10000);
        }catch (Exception e){
            e.printStackTrace();
        }
        return jedisPoolConfig;
    }

    @Bean
    public JedisPool createJedisPool(){
        JedisPool jedisPool = null;
        try{
            //创建jedisPool连接池
            jedisPool = new JedisPool(jedisPoolConfig,host,port,timeout,password,database);
        }catch (Exception e){
            e.printStackTrace();
        }
        return jedisPool;
    }

    @Bean
    public Jedis getJedis(){


            //获取jedis连接对象
            return jedisPool.getResource();

    }
}
